package hzst.android.form;

import hzst.android.BaseActivity;
import hzst.android.Constants;
import hzst.android.R;
import hzst.android.adapter.CommonAdapter;
import hzst.android.form.info.SelectSource;
import hzst.android.form.info.SelectSource.SourceValue;
import hzst.android.form.info.SelectViewInfo;
import hzst.android.form.view.FMSelectView;
import hzst.android.util.L;
import hzst.android.util.NetworkDataUtil;
import hzst.android.view.FooterListView;
import hzst.android.view.FooterListView.OnSlideToBottomListener;
import hzst.android.view.TopNavigationBar;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * 作为{@link FMSelectView}的选择数据列表，当选择了一条或多条数据时，会返回{@link List<SelectSource>}数据，
 * 条目的名称和id需要单独提取出来作为{@link FMSelectView}的传递参数，其他的相关参数用于匹配表单中相同字段的控件(也有可能没有匹配字段)，并给其赋值。
 * @author wt
 *	传值：{@link Bundle} key:"host" {@link #host}
 */
public class SelectSourceListActivity extends BaseActivity{
	private TopNavigationBar tnbSource;
	private FooterListView lvSource;
	
	private SelectViewInfo info; 
	
	private String host;
	private int pageIndex = 1;
	private int pageSize = 10;
	
	private CommonAdapter<SelectSource> adapter;
	private List<SelectSource> selectSources;
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if(adapter == null){
				adapter = new CommonAdapter<SelectSource>(mContext, selectSources, R.layout.adapter_source_item) {

					@Override
					public void convert(ViewHolder helper, SelectSource item,
							int position) {
						helper.setText(R.id.tv_title, item.getItemName());
						LinearLayout llay = helper.getView(R.id.llay_source_content);
						if(llay.getChildCount() == 0){
							List<SourceValue> sourceValues = item.getSourceValues();
							/*
							 * 动态生成条目的信息
							 */
							for (int i = 0; i < sourceValues.size(); i++) {
								SourceValue value = sourceValues.get(i);
								TextView tv = new TextView(mContext);
								tv.setText(value.getTitle()+"："+value.getContent());
								llay.addView(tv);
							}
						}
						
						if(info.isMultiple()){
							CheckBox cb = helper.getView(R.id.cb_source);
							cb.setVisibility(View.VISIBLE);
						}
					}
				};
				lvSource.setAdapter(adapter);
			}else{
				adapter.notifyDataSetChanged();
			}
			lvSource.loadFooterView();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_select_source);
		
		initBaseData();
		initView();
		initEvents();
		
		getData();
	}
	
	@Override
	public void initBaseData() {
		info = (SelectViewInfo) getIntent().getSerializableExtra("viewInfo");
		host = getIntent().getStringExtra("host");
	}

	@Override
	public void initView() {
		tnbSource = (TopNavigationBar) findViewById(R.id.tnb_source);
		tnbSource.setTitle(info.getName());
		lvSource = (FooterListView) findViewById(R.id.lv_source);
		lvSource.setPageSize(pageSize);
	}

	@Override
	public void initEvents() {
		lvSource.setOnSlideToBottomListener(new OnSlideToBottomListener() {
			
			@Override
			public void arriveBottom() {
				pageIndex ++;
				getData();
			}
		});
		lvSource.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				SelectSource item = selectSources.get(position);
				if(info.isMultiple()){
					CheckBox cb = (CheckBox) view.findViewById(R.id.cb_source);
					cb.setChecked(!cb.isChecked());
					item.setSelected(cb.isChecked());
				}else{
					Intent intent = new Intent();
					intent.putExtra("ids", item.getId());
					intent.putExtra("names", item.getItemName());
					intent.putExtra("selectSource", item);
					setResult(Constants.RESULT_SELECT_RESOURCE, intent);
					finish();
				}
			}
		});
	}
	
	private void getData(){
		new Thread(){

			@Override
			public void run() {
				try {
					String url = host+info.getSourceUrl()+"?PageSize="+pageSize+"&PageIndex="+pageIndex;
					L.showLogInfo(L.TAG_NET_REQUEST, "选择数据列表："+url);
					String json = NetworkDataUtil.getJsonData(url);
					parseSource(json);
					handler.sendEmptyMessage(0x123);
				} catch (Exception e) {
					L.showLogInfo(L.TAG_EXCEPTION, e.toString());
				}
			}
			
		}.start();
	}
	/**
	 * 解析数据源
	 * @param json
	 */
	private void parseSource(String json){
		if(selectSources == null){
			selectSources = new ArrayList<SelectSource>();
		}
		try {
			JSONArray array = new JSONArray(json);
			for (int i = 0; i < array.length(); i++) {
				SelectSource source = new SelectSource();
				JSONObject obj = array.getJSONObject(i);
				source.setId(obj.getString("id"));
				source.setItemName(obj.getString("itemName"));
				List<SourceValue> sourceValues = new ArrayList<SelectSource.SourceValue>();
				JSONArray valueArray = new JSONArray(obj.getString("values"));
				for (int j = 0; j < valueArray.length(); j++) {
					SourceValue value = source.new SourceValue();
					JSONObject valueObj = valueArray.getJSONObject(j);
					value.setField(valueObj.getString("field"));
					value.setTitle(valueObj.getString("title"));
					value.setContent(valueObj.getString("content"));
					sourceValues.add(value);
				}
				source.setSourceValues(sourceValues);
				selectSources.add(source);
			}
		} catch (JSONException e) {
			L.showLogInfo(L.TAG_EXCEPTION, e.toString());
		}
	}

}
